#region Using Directives

using System;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework;

using EnvDTE;

#endregion

namespace WiGO.RCX.PF.Actions
{
    class FindSolutionFolderAction : Action
    {
        #region Input Properties

        [Input]
        public string FolderPath
        {
            get { return folderPath; }
            set { folderPath = value; }
        } string folderPath;

        #endregion

        #region Output Properties

        [Output]
        public Project FolderProject
        {
            get { return folderProject; }
            set { folderProject = value; }
        } Project folderProject;

        #endregion

        #region IAction Members

        public override void Execute()
        {
            DTE vs = (DTE)GetService<DTE>(true);
            Solution solution = vs.Solution;
            Projects projects = solution.Projects;
            string[] folderNames = folderPath.Split(new char[] { '.' });

            if (folderNames.Length > 0)
            {
                foreach (Project proj in projects)
                {
                    if (folderNames[0].CompareTo(proj.Name) == 0)
                    {
                        if (folderNames.Length > 1)
                        {
                            folderProject = findChildProject(proj, folderNames, 1);
                        }
                        else
                        {
                            folderProject = proj;
                        }
                        break;
                    }
                }
            }
        }

        private Project findChildProject(Project parent, string[] names, int index)
        {
            Project result = null;
            foreach (ProjectItem item in parent.ProjectItems)
            {
                if (item.Name.CompareTo(names[index]) == 0)
                {
                    result = item.SubProject;
                    if (result != null)
                    {
                        if (index+1==names.Length) {
                            return result;
                        }
                        else 
                        {
                            result = findChildProject(result, names, ++index);
                            break;
                        }
                    }
                    
                }
            }
            return result;
        }

        public override void Undo()
        {
            // throw new Exception("The method or operation is not implemented.");
        }

        #endregion
    }
}
